<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <div>
        <span>发送消息：</span>
        <label>
            <input id="sender"/>
        </label>
        <button onclick="send()">发送</button>
    </div>
    <div>
        <span>收到消息：</span>
        <span id="receiver"></span>
    </div>
    <div>
        <input type="file" id="fileInput" />
        <button onclick="sendFile()">Send File</button>
        <span>上传进度：</span>
        <span id="progress"></span>
    </div>
</div>
<script src="../js/v4.8/socket.io.js"></script>
<script>
    const sender = document.getElementById('sender');
    const receiver = document.getElementById('receiver');

    const socket = io("http://127.0.0.1:8081",{
        transports: ['websocket'],
        path: '/socket.io',
        maxHttpBufferSize: 1e8 // 100 MB);
    });
    function send() {
        const message = sender.value;
        socket.emit('chat', message);
    }
    // 定义两个日期
    let begin;
    function sendFile() {
        begin = new Date();
        document.getElementById("progress").textContent = "0%";
        const fileInput = document.getElementById('fileInput');
        const file = fileInput.files[0];
        if (!file) {
            alert("Please select a file first.");
            return;
        }
        const reader = new FileReader();
        reader.onload = function(event) {
            const arrayBuffer = event.target.result;
            const chunkSize = 1024 * 1024; // 1 MB
            let offset = 0;
            let offset2 = 0;
            while (offset < arrayBuffer.byteLength) {
                const chunk = arrayBuffer.slice(offset, offset + chunkSize);
                const base64Chunk = btoa(new Uint8Array(chunk).reduce((data, byte) => data + String.fromCharCode(byte), ''));
                socket.emit('file_chunk', { filename: file.name, chunk: base64Chunk, offset: offset, totalSize: arrayBuffer.byteLength },function(){
                    offset2 +=chunk.byteLength;
                    // 计算进度
                    let percentage = (offset2/arrayBuffer.byteLength) * 100;
                    if(Math.floor(percentage) <= 100){
                        document.getElementById("progress").textContent = Math.floor(percentage)+"%";
                        if(Math.floor(percentage) === 100) {
                            document.getElementById("progress").textContent = "完成";
                        }
                    }
                    console.log("输出：",offset2,arrayBuffer.byteLength)

                });
                offset += chunkSize;

            }
        };
        reader.readAsArrayBuffer(file);
    }


    function sendFile2() {
        const file = document.getElementById('fileInput').files[0];
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function() {
            const data = reader.result;
            socket.emit('file', data);
        }
    }

    socket.on('connect', () => {
        console.log('Connected to the server');
    });

    socket.on('chat', function(message) {
        console.log('Received message: ', message)
        receiver.textContent = message;
    });

    socket.on('file_received', (filename) => {
        let end = new Date();
        // 计算两个日期之间的差异（以毫秒为单位）
        let diffInMilliseconds = Math.abs(end  - begin);
        // 转换为天数
        let diffInDays = diffInMilliseconds / (1000 * 60 * 60 * 24);
        /*alert(`File ${filename} received successfully. 传输耗时：${diffInMilliseconds} 毫秒`);*/
        console.log(`File ${filename} received successfully. 传输耗时：${diffInMilliseconds} 毫秒`);
    });
</script>
</body>
</html>